import * as _wechat from '@/utils/wechat'
import * as $auth from '@/api/auth'
import {mapActions, mapState, mapGetters} from 'vuex'
import {wxLogin} from '@/graphql/auth'
const VERSION = '111'

export default {
  data () {
    return {
      isShowSideMenu: false,
      isLoading: false,
      isPageLoading: false,
      isPageNeedAuthUser: false,
      appVersion: '105'
    }
  },
  computed: {
    ...mapGetters([
      'role',
      'loginer',
      'groupId',
    ])
  },
  onLoad () {
    let version = wx.getStorageSync('version') || ''
    if (version !== VERSION) {
      this.setRole('')
      this.resetLoginer()
      wx.setStorageSync('version', VERSION)
    }
  },
  onShow () {
    this.onPageShow()
    let currentPath = this.getCurrentPath()
    if (!this.role && currentPath !== 'pages/index/main') {
      wx.navigateTo({
        url: '/pages/index/main'
      })
      return
    }
    this.setIsAppShow(true)
    this.switchRole()
    this.auth().catch(e => {
      console.error(e)
    })
    let {isShowSideMenu = 'n'} = this.getParams()
    this.isShowSideMenu = isShowSideMenu === 'y'
  },
  onHide () {
    this.setIsAppShow(false)
    this.setIsPageLoading(false)
    this.onPageHide()
  },
  onUnload () {
    this.setIsAppShow(false)
    this.setIsPageLoading(false)
    this.onPageHide()
  },
  methods: {
    onPageShow () {},
    onPageHide () {},
    async loginBack (loginer) {
      this.$store.commit('AUTH_SET_IS_LOGINED', true)
      try {
        let gid = await this.genGroup()
        this.groupBack(loginer, gid)
      } catch (e) {
        wx.showModal({title: 'gen group error!'})
      }
    },
    async genGroup () {
      let {shareTicket, groupOwnerId = 0} = this.$root.$mp.appOptions
      if (!shareTicket) {
        if (this.groupId) return this.groupId
        this.setGroupId(0)
        return 0
      }

      let rs = await _wechat.getShareInfo(shareTicket)
      let {encryptedData, iv} = rs
      let groupId = await this.fetchGroup({encryptedData, iv, groupOwnerId})
      return groupId
    },
    groupBack (loginer, gid) {},
    ...mapActions([
      'login',
      'checkSession',
      'fetchGroup',
      'setGroupId',
      'setIsNeedAuthUserInfo',
      'setIsPageLoading',
      'setIsAppShow',
      'resetLoginer',
      'setRole',
      'setIsPageLoading'
    ]),
    checkAuthUserInfo (loginer) {
      let {nickName} = loginer
      if (!nickName) {
        this.setIsNeedAuthUserInfo(true)
      }
    },
    async auth () {
      try {
        let {token} = this.loginer
        if (!token) {
          let flag = await this.login()
          if (!flag) {
            wx.showModal({title: 'login fail!'})
            return
          }
          if (this.isPageNeedAuthUser) {
            this.checkAuthUserInfo(this.loginer)
          }
          await this.loginBack(this.loginer)
          return
        }

        if (this.isPageNeedAuthUser) {
          this.checkAuthUserInfo(this.loginer)
        }
        await this.loginBack(this.loginer)
      } catch (e) {
        throw e
        wx.showModal({title: '认证失败！'})
      }
    },
    switchRole () {
      if (this.role === 'student') {
        wx.setNavigationBarColor({
          backgroundColor: '#0097B4',
          frontColor: '#ffffff'
        })
      } else {
        wx.setNavigationBarColor({
          backgroundColor: '#ffffff',
          frontColor: '#000000'
        })
      }
    },
    getCurrentPage () {
      let pages = getCurrentPages()
      let currentPage = pages[pages.length - 1]
      return currentPage
    },
    getParams () {
      let currentPage = this.getCurrentPage()
      let options = currentPage.options || {}
      return options
    },
    getCurrentPath () {
      let currentPage = this.getCurrentPage()
      let url = currentPage.route || ''
      return url
    },
  },
}
